import useI18n from '@/i18n'
import axios from 'axios'
import errorCode from '@/utils/errorCode'
import {defaultTo, errorRequest, getToken, hrefRemoveToken, tansParams} from '@/utils/setting.js'
import {ElMessage} from "element-plus";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const i18n = useI18n.global
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时
  timeout: 10000
})

// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    }
    const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
    const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
    if (requestSize >= limitSize) {
      console.warn(`[${config.url}]: ` + i18n.t('utils.request.434641-0'))
      return config;
    }
  }
  return config
}, error => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    const { showMessage = true } = res.config
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    const isLoginCode = [40101, 40107]
    const is401Code = [40100, 40102, 40103, 40104, 40105, 40106, 500]
    // 二进制数据则直接返回
    if (res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer') {
      return res.data
    }
    // token过期/套餐过期后后清除路由上的token
    /*if (isLoginCode.includes(code)) {
      sessionStorage.setItem('is404', 'false')
      hrefRemoveToken()
      return Promise.reject('error')
    } else if (is401Code.includes(code)) {
      sessionStorage.setItem('is404', 'true')
      hrefRemoveToken()
      return Promise.reject('error')
    } else if (code !== 200) {
      if(showMessage) ElMessage.error(msg)
      return Promise.reject('error')
    } else {
      return Promise.resolve(res.data)
    }*/
    if (code === 200) {
      return Promise.resolve(errorRequest(res))
    } else {
      return Promise.reject(errorRequest(res))
    }
  },
  error => {
    if (error.config.url !== '/pay/userPack/verifyKey') {
      sessionStorage.setItem('is404', 'true')
      hrefRemoveToken()
    }
    return Promise.reject(error)
  }
)

// 上传文件
export const uploadFile = (files, url)=>{
  const formData = new FormData();
  for(let key in files) {
    formData.append(key, files[key]);
  }
  return axios.post(`${import.meta.env.VITE_APP_BASE_API}${url}`, formData, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Bearer ' + getToken()
    }
  }).then(response => {
    const code = response.data.code || response.code || 200
    const msg = response.data.msg || response.msg || errorCode[code] || response.data.msg || errorCode['default']
    if (code == 401 || code == 500) {
      // window.location.reload()
      // ElMessage.error(i18n.t('utils.request.434641-2'))
      ElMessage({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else {
      return Promise.resolve(response.data)
    }
  }).catch((error) => {
    return Promise.reject(error)
  })
}

export default service
